﻿using System;
using System.Collections.Generic;
using System.Text;
using SlimDX.Direct3D9;

namespace Terrain
{
	/// <summary>
	/// Klasa której instancje reprezentują obiekt modelu 3D wczytanego z pliku 
	/// </summary>
	class MeshObject
	{
		///Obiekt modelu
		public Mesh mesh;
		private Material[] materials;
		public Texture[] textures;
		///Katalog przechowujacy modele 3D
		public static string directory = "../../";

		private Device device;

		///Konstruktor
		public MeshObject(Device device)
		{
			this.device = device;
		}

		///Metoda wczytuje model z pliku
		public bool LoadMesh(string filename) // from an .x file
		{
			ExtendedMaterial[] materialArray;
			mesh = Mesh.FromFile(device, directory + filename, MeshFlags.Managed);
			mesh.ComputeNormals();
			materialArray = mesh.GetMaterials();
			

			if ((materialArray != null) && (materialArray.Length > 0))
			{
				materials = new Material[materialArray.Length];
				textures = new Texture[materialArray.Length];

				for (int i = 0; i < materialArray.Length; i++)
				{
					materials[i] = materialArray[i].MaterialD3D;
					materials[i].Ambient = materials[i].Diffuse;

					if ((materialArray[i].TextureFileName != null) && (materialArray[i].TextureFileName != string.Empty))
					{
						textures[i] = Texture.FromFile(device, directory + materialArray[i].TextureFileName);
					}
				}
			}
			
			return true;
		}

		///Metoda rysuje model
		public void Draw()
		{
			for (int i = 0; i < materials.Length; i++)
			{
				device.Material = materials[i];
				device.SetTexture(0, textures[i]);
				mesh.DrawSubset(i);
			}
		}
	}
}
